import {takeEvery, select, call, put, take} from 'redux-saga/effects'
import axios from 'axios'
import { message } from 'antd';
import { duration } from 'moment';

// 引入自定义操作
import { ChangeTasksActivate, GiveUpWorkerTaskSaga } from '../actions/taskWorkerManagePage'

// 引入常量
import { GETWORKERTASKSSAGA, CHANGEWORKERTASKSAGA, GIVEUPWORKERTASKSAGA } from '../constants'
import { API_URL } from '../../env';


// 猎人管理任务页面
function* getWorkerTasksSaga(action) {
    try{
        const res = yield call(axios.post, API_URL + "manage/worker_tasks", {...action.data})
        if (res.status == 200){
            yield put(ChangeTasksActivate({task_data: res.data.task_data}))
        } else {
            message.error('请求失败')
        }
        console.log("请求后端猎人任务，res为：", res)
    } catch(e) {
        message.error('请求失败')
    }
}

// 猎人向后端发送，修改任务状态
function* changeWorkerTaskSaga(action) {
    const obj = {
        id: action.data.key,
        res: action.data.task_res[0]
    }
    console.log("changeWorkerTaskSaga is ", obj)
    try{
        const res = yield call(axios.post, API_URL + "manage/change_worker_task_res", {...obj})
        if (res.status == 200) {
            // 先提示，再刷新
            message.success('任务状态更改成功', duration=0.1).then(()=>{window.location.reload()})
        } else {
            message.error("请求失败")
        }
    } catch(e) {
        message.error("请求失败")
    }
}

// 猎人向后端发送，放弃任务，已完成的任务无法放弃
function* giveUpWorkerTaskSaga(action) {
    const obj = {
        id: action.data.key,
        res: action.data.task_res[0]
    }
    console.log("changeWorkerTaskSaga is ", obj)
    try{
        const res = yield call(axios.post, API_URL + "manage/give_up_worker_task", {...obj})
        if (res.status == 200) {
            message.success('任务放弃成功，望下次执行任务成功', duration=0.1).then(()=>{window.location.reload()})
        } else {
            message.error("请求失败")
        }
    }catch (e) {
        message.error("请求失败")
    }
}

export function* taskWorkerManagePageSaga () {
    yield takeEvery(GETWORKERTASKSSAGA, getWorkerTasksSaga)
    yield takeEvery(CHANGEWORKERTASKSAGA, changeWorkerTaskSaga)
    yield takeEvery(GIVEUPWORKERTASKSAGA, giveUpWorkerTaskSaga)
}
